package com.servlet;

import com.pojo.Resources;
import com.pojo.User;
import com.service.ResourcesService;
import com.service.UserService;
import com.service.impl.ResourcesServiceImpl;
import com.service.impl.UserServiceImpl;
import com.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet("/user")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();
    ResourcesService resourcesService = new ResourcesServiceImpl();

    public ResultData toLogin(HttpServletRequest request, HttpServletResponse response){
            String name = request.getParameter("name");
        String password = request.getParameter("password");
        User user = new User();
        user.setUserName(name);
        user.setPassword(password);
        ResultData<User> resultData = new ResultData<User>();
        User user1 = userService.findUser(user);
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user1);
        if(user1 !=null){
            resultData.setMsg("登录成功");
            resultData.setStatus(200);
            resultData.setData(user1);
        }
        return resultData;
    }

    public ResultData delUser(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        int id1 = userService.delUserById(id);
        ResultData<User> resultData = new ResultData<User>();
        if(id1>0){
            resultData.setMsg("删除成功");
            resultData.setStatus(200);
        }
        return resultData;
    }

    public String selectOneUser(HttpServletRequest request, HttpServletResponse response){
            int id = Integer.parseInt(request.getParameter("id"));
            User user = new User();
            user.setId(4);
            user.setAccountName("admin");
            user.setUserName("admin");
            user.setPassword("123456");
            HttpSession session = request.getSession(true);
            session.setAttribute("user1",user);
            return "system/user/userInfo";
    }

    public String fileUpload(HttpServletRequest request, HttpServletResponse response){

        return "system/user/fileUpload";
    }

    public ResultData upload(HttpServletRequest request, HttpServletResponse response){
        System.out.println("dddd");
        //解析请求之前先判断请求类型是否为文件上传类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //指定上传位置
        String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");

        //服务器地址
         String path1="http://47.100.193.239:9950/upload/schoolcms/images";

        //完整路径
        StringBuffer stringPath = new StringBuffer();
        File saveDir = new File(uploadFilePath);
        //如果目录不存在，就创建目录
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        System.out.println("dddd");
        if(isMultipart){
            //创建文件上传核心类
            FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
            ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
            try{
                //处理表单请求
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while(iter.hasNext()){
                    FileItem item = (FileItem)iter.next();
                      // 如果为文件域
                    File file = new File(item.getName());// 获得文件名(全路径)
                    String string = UUID.randomUUID().toString();
                    stringPath=new StringBuffer(string+file.getName());
                    File saveFile = new File(uploadFilePath,stringPath.toString());//将文件保存到指定的路径
                    item.write(saveFile);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        ResultData<User> resultData = new ResultData<User>();
        resultData.setMsg(stringPath.toString());
        resultData.setStatus(200);
        return resultData;
    }


    public ResultData insertFile(HttpServletRequest request, HttpServletResponse response){
        String uname =request.getParameter("uname");
        String password =request.getParameter("password");
        String[] paths = request.getParameterValues("path");
        List<String> list = Arrays.asList(paths);
        StringBuffer stringBuffer = new StringBuffer();
        for (String str:list) {
            stringBuffer.append(str+",");
        }
        String strPath = stringBuffer.toString();
        ResultData<User> resultData = new ResultData<User>();
        User user = new User();
        user.setUserName(uname);
        user.setPassword(password);
        user.setPicPath(strPath);
        int i = userService.addUser(user);
        if(i>0){
            resultData.setMsg("上传成功");
            resultData.setStatus(200);
        }
        return resultData;

    }


    public LayuiTable<User> allUser(HttpServletRequest request, HttpServletResponse response){
        int page = request.getParameter("page")!=null?Integer.parseInt(request.getParameter("page")):1;
        int limit = request.getParameter("limit")!=null?Integer.parseInt(request.getParameter("limit")):10;

        LayuiTable<User> layuiTable=userService.findAll(page,limit);
        return layuiTable;
    }




    public String userIndex(HttpServletRequest request, HttpServletResponse response){
       // List<User> all = userService.findAll();
        HttpSession session = request.getSession(true);
        //查询当前用户所拥有的菜单权限
        int id = Integer.parseInt(request.getParameter("id"));
        List<Resources> resourcesList = resourcesService.findAll(id);
        session.setAttribute("resourcesList",resourcesList);
        return "index";
    }

    public String getMenuBtn(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(true);
        User user = (User)session.getAttribute("user");
        int uid=user.getId();
        int mid = Integer.parseInt(request.getParameter("mid"));
        List<Resources> resourcesList = resourcesService.findAll(uid,mid);
        session.setAttribute("userMenuBtn",resourcesList);
        return "system/user/userList";
    }



    public String getUserById(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        User user = userService.findUser(id);
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        return "modifyUser";
    }
    public ResultData doUpdateUser(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("uid"));
        String name = request.getParameter("name");
        String password = request.getParameter("pass");
        String realName = request.getParameter("realName");
        int sex = Integer.parseInt(request.getParameter("sex"));

        User user = new User();
        user.setId(id);
        user.setUserName(name);
        user.setPassword(password);
        user.setAccountName(realName);
        user.setSex(sex);
        ResultData<User> resultData = new ResultData<User>();
        int i = userService.doUpadateUser(user);
        if(i>0){
            resultData.setMsg("修改成功");
            resultData.setStatus(200);
        }
        return resultData;

    }




    @Override
    public Class<?> getServletClass() {
        return UserServlet.class;
    }
}
